<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\StoreCategory;
use App\Models\Goods;
use App\Models\Category;
use App\Models\GoodsCategory;
use App\Models\Address;
use App\Services\ImageUrlService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    /**
     * 获取分类列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCategories(Request $request)
    {
        try {
            // 获取参数，支持嵌套的param结构
            $param = $request->input('param', []);
            $keyword = $param['keyword'] ?? $request->input('keyword', '');
            
            \Log::info('getCategories接收参数 - keyword: ' . $keyword);
            
            // 以商品分类关联表为主，获取有商品的分类ID（去重）
            $goodsCategoryQuery = GoodsCategory::select('ims_yz_goods_category.category_id')
                ->distinct()
                ->join('ims_yz_goods', 'ims_yz_goods_category.goods_id', '=', 'ims_yz_goods.id')
                ->where('ims_yz_goods.status', 1); // 只查询上架商品
            
            // 关键词搜索时，通过商品名称搜索
            if (!empty($keyword)) {
                $goodsCategoryQuery->where('ims_yz_goods.title', 'like', '%' . $keyword . '%');
                \Log::info('getCategories关键字搜索商品名称: ' . $keyword);
            }
            
            $categoryIds = $goodsCategoryQuery->pluck('category_id')->toArray();
            
            if (empty($categoryIds)) {
                return response()->json([
                    'code' => 200,
                    'message' => '查询成功',
                    'data' => [
                        'categories' => []
                    ]
                ]);
            }
            
            // 获取这些分类的详细信息
            $categories = Category::whereIn('id', $categoryIds)
                ->where('enabled', 1)
                ->orderBy('display_order', 'asc')
                ->get();
            
            // 分离一级和二级分类
            $firstLevelCategories = $categories->where('parent_id', 0);
            $secondLevelCategories = $categories->where('parent_id', '>', 0);
            
            // 获取二级分类的父分类ID
            $parentIds = $secondLevelCategories->pluck('parent_id')->unique()->toArray();
            
            // 获取父分类信息
            $parentCategories = Category::whereIn('id', $parentIds)
                ->where('enabled', 1)
                ->orderBy('display_order', 'asc')
                ->get();
            
            // 将父分类和子分类合并
            $allCategories = $firstLevelCategories->merge($parentCategories);
            
            // 将二级分类按父分类分组
            $secondLevelGrouped = $secondLevelCategories->groupBy('parent_id');
            
            // 构建分类树结构
            $categoriesData = $allCategories->map(function ($category) use ($secondLevelGrouped) {
                $children = $secondLevelGrouped->get($category->id, collect());
                
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'thumb' => ImageUrlService::processImageUrl($category->thumb),
                    'display_order' => $category->display_order,
                    'parent_id' => $category->parent_id,
                    'level' => $category->level,
                    'children' => $children->map(function ($child) {
                        return [
                            'id' => $child->id,
                            'name' => $child->name,
                            'thumb' => $child->thumb ? asset('storage/' . $child->thumb) : '',
                            'display_order' => $child->display_order,
                            'parent_id' => $child->parent_id,
                            'level' => $child->level
                        ];
                    })->toArray()
                ];
            });
            
            return response()->json([
                'code' => 200,
                'message' => '查询成功',
                'data' => [
                    'categories' => $categoriesData
                ]
            ]);
            
        } catch (\Exception $e) {
            \Log::error('获取分类失败: ' . $e->getMessage());
            return response()->json([
                'code' => 500,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 搜索商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchGoods(Request $request)
    {
        try {
            // 获取参数，支持嵌套的param结构
            $param = $request->input('param', []);
            $keyword = $param['keyword'] ?? $request->input('keyword', '');
            $firstCategoryId = $param['first_category_id'] ?? $request->input('first_category_id', 0);
            $secondCategoryId = $param['second_category_id'] ?? $request->input('second_category_id', 0);
            $page = $param['page'] ?? $request->input('page', 1);
            $limit = $param['limit'] ?? $request->input('limit', 20);
            
            \Log::info('searchGoods接收参数 - keyword: ' . $keyword . ', first_category_id: ' . $firstCategoryId . ', second_category_id: ' . $secondCategoryId);
            
            // 构建基础查询 - 直接查询商品表
            $baseQuery = Goods::select([
                'ims_yz_goods.id',
                'ims_yz_goods.title',
                'ims_yz_goods.thumb',
                'ims_yz_goods.price',
                'ims_yz_goods.market_price',
                'ims_yz_goods.status'
            ])
            ->where('ims_yz_goods.status', 1); // 只查询上架商品
            
            // 关键词搜索商品名称
            if (!empty($keyword)) {
                $baseQuery->where('ims_yz_goods.title', 'like', '%' . $keyword . '%');
                \Log::info('关键字搜索商品名称: ' . $keyword);
            }
            
            // 分类筛选
            $goodsIds = [];
            
            // 调试信息
            \Log::info('分类筛选参数 - first_category_id: ' . $firstCategoryId . ', second_category_id: ' . $secondCategoryId);
            
            // 检查商品分类关联表是否有数据
            $hasGoodsCategoryData = GoodsCategory::count() > 0;
            \Log::info('商品分类关联表是否有数据: ' . ($hasGoodsCategoryData ? '是' : '否'));
            
            if ($hasGoodsCategoryData) {
            // 如果指定了二级分类，优先使用二级分类
            if (!empty($secondCategoryId) && $secondCategoryId > 0) {
                $goodsIds = GoodsCategory::where('category_id', $secondCategoryId)
                    ->pluck('goods_id')
                    ->toArray();
                \Log::info('二级分类筛选 - category_id: ' . $secondCategoryId . ', goods_ids: ' . json_encode($goodsIds));
            }
            // 如果指定了一级分类但没有二级分类，查询该一级分类下所有二级分类的商品
            elseif (!empty($firstCategoryId) && $firstCategoryId > 0) {
                // 获取该一级分类下的所有二级分类ID
                $secondCategoryIds = Category::where('parent_id', $firstCategoryId)
                    ->where('enabled', 1)
                    ->pluck('id')
                    ->toArray();
                
                \Log::info('一级分类下的二级分类IDs: ' . json_encode($secondCategoryIds));
                
                if (!empty($secondCategoryIds)) {
                    $goodsIds = GoodsCategory::whereIn('category_id', $secondCategoryIds)
                        ->pluck('goods_id')
                        ->toArray();
                    \Log::info('一级分类筛选 - first_category_id: ' . $firstCategoryId . ', goods_ids: ' . json_encode($goodsIds));
                }
            }
            // 如果分类ID都是0，查询所有商品
            else {
                \Log::info('分类ID都是0，查询所有商品');
                $goodsIds = []; // 空数组表示不进行分类筛选
            }
                
                // 如果有分类筛选条件，应用筛选
                if (!empty($goodsIds)) {
                    $baseQuery->whereIn('ims_yz_goods.id', $goodsIds);
                    \Log::info('应用分类筛选，商品ID数量: ' . count($goodsIds));
                } else {
                    // 如果goodsIds为空数组，说明是查询所有商品（分类ID都是0）
                    // 或者没有找到对应的商品分类关联数据
                    if ($firstCategoryId == 0 && $secondCategoryId == 0) {
                        \Log::info('分类ID都是0，查询所有商品');
                    } else {
                        \Log::info('没有找到对应的商品分类关联数据，返回空数组');
                        // 如果没有找到对应的商品，返回空结果
                        return response()->json([
                            'code' => 200,
                            'message' => '查询成功',
                            'data' => [
                                'goods' => [],
                                'pagination' => [
                                    'page' => $page,
                                    'limit' => $limit,
                                    'total' => 0,
                                    'total_pages' => 0,
                                    'has_more' => false
                                ]
                            ]
                        ]);
                    }
                }
            } else {
                \Log::info('商品分类关联表为空，忽略分类筛选，返回所有商品');
            }
            
            // 排序
            $baseQuery->orderBy('ims_yz_goods.id', 'desc');
            
            // 获取总数
            $total = $baseQuery->count();
            
            // 分页查询
            $goods = $baseQuery->offset(($page - 1) * $limit)
                ->limit($limit)
                ->get();
            
            // 处理商品数据
            $goodsList = $goods->map(function ($item) {
                return [
                    'id' => $item->id,
                    'title' => $item->title,
                    'thumb' => ImageUrlService::processImageUrl($item->thumb),
                    'price' => $item->price,
                    'market_price' => $item->market_price
                ];
            });
            
            $totalPages = ceil($total / $limit);
            
            return response()->json([
                'code' => 200,
                'message' => '查询成功',
                'data' => [
                    'goods' => $goodsList,
                    'pagination' => [
                        'page' => $page,
                        'limit' => $limit,
                        'total' => $total,
                        'total_pages' => $totalPages,
                        'has_more' => $page < $totalPages
                    ]
                ]
            ]);
            
        } catch (\Exception $e) {
            \Log::error('搜索商品失败: ' . $e->getMessage());
            return response()->json([
                'code' => 500,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }
    
}
